import { ref, VNodeChild } from 'vue'
import {
    createDiscreteApi,
    MessageOptions,
    type MessageReactive,
    useOsTheme,
    darkTheme,
    lightTheme,
    ConfigProviderProps
} from 'naive-ui'
import { GLOBAL_CONFIG } from '@/config/constant'
import { useGlobalStore } from '@/store'

type Options = {
    content: string | (() => VNodeChild)
    type?: MessageOptions['type']
}

const themeOs = useOsTheme()
function getThemed(): ConfigProviderProps['theme'] {
    try {
        const globalStore = useGlobalStore()
        return globalStore.themed
    } catch (_) {
        let themed: typeof darkTheme | typeof lightTheme
        const sessionGlobal = sessionStorage.getItem(GLOBAL_CONFIG)
        let theme = themeOs.value
        if (sessionGlobal) {
            theme = JSON.parse(sessionGlobal).theme
        }

        if (theme === 'dark') {
            themed = darkTheme
        } else if (theme === 'light') {
            themed = lightTheme
        } else {
            themed = themeOs.value === 'dark' ? darkTheme : lightTheme
        }

        return themed
    }
}

export default function useMessageApi() {
    const { message } = createDiscreteApi(['message'], {
        configProviderProps: {
            theme: getThemed()
        }
    })

    const ins = ref<MessageReactive | null>(null)

    /**
     * 设置消息
     * @param options Options 默认关闭
     */
    const setMessage = (options?: Options) => {
        if (options) {
            if (ins.value) {
                ins.value.content = options.content
                ins.value.type = options.type || 'success'
                ins.value.duration = options.type === 'error' ? 3000 : 1000
            } else {
                ins.value = message.create(options.content, {
                    type: 'loading',
                    duration: 6000
                })
            }
        } else {
            if (ins.value) ins.value.destroy()
        }
    }

    return {
        messageIns: ins,
        setMessage
    }
}
